package com.qf.hospital.controller;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageInfo;
import com.qf.hospital.VO.MenuDTreeVO;
import com.qf.hospital.VO.R;
import com.qf.hospital.VO.SysMenuVO;
import com.qf.hospital.entity.SysMenu;
import com.qf.hospital.service.SysMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 何星宇
 * @version V1.0
 * @Date 2021/10/19 19:22
 */

@RestController
public class MenuController {
    private Logger log = LoggerFactory.getLogger(MenuController.class);
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 查询所有菜单（左侧菜单树）
     * @return
     */
    @PostMapping("/sel/loadMenuMangerLeftTreeJson")
    public R loadMenuLeftTreeJson(Integer spread){
        //调用service查询所有菜单
        List<SysMenu> sysMenuList = sysMenuService.findAll();
        //封装
        List<MenuDTreeVO> data = new ArrayList<>();

        if (spread!=null){
            for (SysMenu sysMenu : sysMenuList) {
                if (sysMenu.getParentId()==0||sysMenu.getParentId()==1){
                    MenuDTreeVO menuDTreeVO = new MenuDTreeVO();
                    BeanUtils.copyProperties(sysMenu, menuDTreeVO);
                    data.add(menuDTreeVO);
                }
            }
        }else {
            for (SysMenu sysMenu : sysMenuList) {
                MenuDTreeVO menuDTreeVO = new MenuDTreeVO();
                BeanUtils.copyProperties(sysMenu, menuDTreeVO);
                data.add(menuDTreeVO);
            }
        }
        return R.ok(data);
    }

    /**
     * 根据条件查询菜单
     * @param id
     * @param title
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/sel/queryMenuAllList")
    public R queryMenuAllList(Integer id,
                              String title,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer limit){

        if (!StringUtils.isEmpty(title)){
            title = "%"+title+"%";
        }
        //调用service查询数据
        PageInfo<SysMenu> pageInfo = sysMenuService.findMenuByParentId(id,title,page,limit);

        //封装数据
        long count = pageInfo.getTotal();
        List<SysMenu> sysMenuList = pageInfo.getList();
        List<SysMenuVO> data = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            SysMenuVO sysMenuVO = new SysMenuVO();
            BeanUtils.copyProperties(sysMenu, sysMenuVO);
            data.add(sysMenuVO);
        }

        return R.ok(data, count);
    }
}
